//
//  CommontTableViewController.swift
//  osc
//
//  Created by admin on 14/11/3.
//  Copyright (c) 2014年 sinosun. All rights reserved.
//

import UIKit

let COMMENT_CELL = "COMMENT_CELL"
class CommontTableViewController: UITableViewController, UIWebViewDelegate {

    var id: Int = 0
    @IBOutlet var navigationItem_my: UINavigationItem!
    @IBOutlet var rigthBarButtonItem: UIBarButtonItem!
    var comments: CommentList = CommentList()
    var pageIndex: Int = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.registerNib(UINib(nibName: "CommentTableViewCell", bundle: nil)!, forCellReuseIdentifier: "COMMENT_CELL")
        self.refreshControl = UIRefreshControl()
       // refreshControl?.attributedTitle = NSAttributedString(string: "正在加载")
        refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
        
        comments = CommentList()
        println("id=\(self.id)")
        var parameters:[String: AnyObject] = ["id": self.id, "catalog": "1", "access_token": access_token,  "page/pageIndex": pageIndex, "pageSize": page_sise, "dataType": dataType]
        loadData(parameters, url: api_comment_list)
    }
    
    func loadData(parameters: [String: AnyObject], url: String){
        HttpClient.loadData(url, parameters: parameters, success: { () -> Void in
            self.tableView.reloadData()
            if self.refreshControl!.refreshing {
                self.refreshControl?.endRefreshing()
            }
        }) { (data) -> Void in
            //self.comments = CommentList(JSONDecoder(data))
            self.comments.append(CommentList(JSONDecoder(data)).commentList)
        }
    }
    func refresh(sender: AnyObject){
        println("重新加载！  ")
        self.comments.commentList.removeAll(keepCapacity: false)
        self.refreshControl?.beginRefreshing()
        var parameters:[String: AnyObject] = ["id": self.id, "catalog": "1", "access_token": access_token,  "page/pageIndex": pageIndex, "pageSize": page_sise, "dataType": dataType]
        loadData(parameters, url: api_comment_list)
    }
    
    @IBAction func postComment(sender: AnyObject) {
        println("postComment")
        performSegueWithIdentifier("postComment", sender: sender)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        var count = self.comments.count
        if count >= 20 {
            count += 1
        }else {
            //do nothing
        }
        return count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(COMMENT_CELL, forIndexPath: indexPath) as CommentTableViewCell
        
        // Configure the cell...
        if indexPath.row >= self.comments.count {
            cell.contentWebView.loadHTMLString("加载更多", baseURL: NSURL(string: baseUrl))

            cell.myImageView.image = nil
            cell.nameAndTime.text = nil
        }else {
            //标题
            var commentM = self.comments.commentList[indexPath.row]
            var commentMV = CommentDetailMV(commentDetailM: commentM)
            cell.nameAndTime.text = commentMV.nameAndTime
            
            //评论内容
            cell.contentWebView.loadHTMLString(commentM.content, baseURL: nil)
            //头像
            var url_str: String? = commentMV.portrait_image_url
            if url_str == nil || url_str == "" {
                url_str = "http://www.oschina.net/img/portrait.gif"
            }
            var url = NSURL(string: url_str!)
            var data = NSData(contentsOfURL: url!)
            var image = UIImage(data: data!)
            cell.myImageView.image = image
        }


        
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        var height: CGFloat = 70
//        var comment = self.comments.commentList[indexPath.row]
//        var commentMV = CommentDetailMV(commentDetailM: comment)
//        println("commentMV.height=\(commentMV.height)")
//        if commentMV.height > 30{
//            height = commentMV.height! + 34 + 70
//        }
//        
//        return height
        var height: CGFloat = 80.0
        if indexPath.row < self.comments.commentList.count {
            var comment = self.comments.commentList[indexPath.row]
            var commentMV = CommentDetailMV(commentDetailM: comment)
            var str = commentMV.content!
            var constraint: CGSize = CGSizeMake(224, 20000.0)
            var attributedText: NSAttributedString = NSAttributedString(string: str , attributes: [NSFontAttributeName : UIFont.systemFontOfSize(14.0)])
            
            var rect: CGRect = attributedText.boundingRectWithSize(constraint, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
            
            var size = rect.size
            height = size.height
        }
        

        
        if height < 30 {
            return 80
        }else{
            return height + 90
        }
        
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        println("回复")
        if indexPath.row >= self.comments.count {
            pageIndex += 1
            var parameters:[String: AnyObject] = ["id": self.id, "catalog": "1", "access_token": access_token,  "page/pageIndex": pageIndex, "pageSize": page_sise, "dataType": dataType]
            loadData(parameters, url: api_comment_list)
        }
        
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */
    


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

}
